$(function () {
    // $.ajax({
    //     url: bignews.category_list,
    //     headers: { Authorization: localStorage.getItem('token') },
    //     success: function (res) {
    //         console.log(res)
    //         let html = template('textfenlei', res)
    //         $('.common_con tbody').html(html)
    //     },
    //     dataType: 'json'
    // })

    //分类数据动态渲染
    function init() {
        $.ajax({
            url: bignews.category_list,
            headers: { Authorization: localStorage.getItem('token') },
            success: function (res) {
                let html = template('alltext', res)
                $('tbody').html(html)
            },
            dataType: 'json'
        })
    }
    init()




    //新增模态框
    $('#xinzengfenlei').on('click', function () {
        $('#add').modal('show')
        $('.modal-title').text('新增分类')
        $('.textadd').text('新增')
        $('#catename').val('')
        $('#cateslug').val('')
    })
    //确定按钮
    //定义一个全局的id,以便下边确定按钮使用
    let id = undefined
    $('.textadd').on('click', function () {
        //获取值
        let name = $('#catename').val()
        let slug = $('#cateslug').val()
        if ($('.textadd').text() == '新增') {
            $.ajax({
                url: bignews.category_add,
                type: 'post',
                headers: { Authorization: localStorage.getItem('token') },
                data: { name, slug },
                success: function (res) {
                    $('#add').modal('hide')
                    if (res.code === 201) {
                        alert(res.msg)
                    }
                    location.reload()
                },
                dataType: 'json'
            })
        } else {
            $.ajax({
                url: bignews.category_edit,
                type: 'post',
                data: { id, name, slug },
                headers: { Authorization: localStorage.getItem('token') },
                success: function (res) {
                    console.log(res)
                    $('#add').modal('hide')
                    if (res.code === 200) {
                        alert(res.msg)
                    }
                    location.reload()
                },
                dataType: 'json'
            })
        }
    })
    //取消按钮
    $('.textremove').on('click', function () {
        $('#catename').val('')
        $('#cateslug').val('')
    })

    //编辑按钮点击
    $('tbody').on('click', '.bianji', function () {
        $('#add').modal('show')
        $('.modal-title').text('编辑分类')
        $('.textadd').text('编辑')
        //获取data-开头的自定义属性的值
        let data = $(this).data()
        console.log(data)
        id = data.id
        $('#catename').val(data.name)
        $('#cateslug').val(data.slug)
    })


    $('#add').on('show.bs.modal', function (e) {
        console.log(e)
    })
})